package map.android.baidu.carpool.utils;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import com.baidu.components.api.extra.APIProxy;

import java.util.List;

public class SafeUtils {

	public static boolean safeEquals(Object o1, Object o2) {
		if (o1 == null || o2 == null) {
			return false;
		}

		return o1.equals(o2);
	}

	public static boolean safeEqualsWithNull(Object o1, Object o2) {
		if (o1 == null && o2 == null) {
			return true;
		}

		if (o1 != null) {
			return o1.equals(o2);
		}

		return false;
	}

	public static int safeString2int(String num) {
		try {
			return Integer.parseInt(num);
		} catch (Exception e) {
		}

		return 0;
	}

	public static long safeString2long(String st) {
		try {
			return Long.parseLong(st);
		} catch (Exception e) {
		}

		return 0;
	}

	public static float safeString2float(String str) {
		try {
			return Float.parseFloat(str);
		} catch (Exception e) {
		}
		return 0f;
	}

	public static double safeString2double(String str) {
		try {
			return Double.parseDouble(str);
		} catch (Exception e) {
		}
		return 0f;
	}
	
	public static boolean safeString2boolean(String str) {
		try {
			if (TextUtils.isEmpty(str)) {
				return false;
			}
			if (str.equals("0")) {
				return false;
			}else if (str.equals("1")) {
				return true;
			}else {
				return false;
			}
		} catch (Exception e) {
		}
		return false;
	}

	public static boolean safeStringEmpty(String s) {
		return TextUtils.isEmpty(s) || "null".equals(s);
	}

	public static int safeGetListSize(List<?> list) {
		return list == null ? 0 : list.size();
	}
	
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}  
	
	public static int dip2px(Context context, float dipValue){ 
        final float scale = context.getResources().getDisplayMetrics().density; 
        return (int)(dipValue * scale + 0.5f); 
}

    public static void safeSetBackground(int resId, View view){

        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackgroundDrawable(APIProxy.res().getResources()
                    .getDrawable((resId)));
        } else {
            view.setBackground(APIProxy.res().getResources()
                    .getDrawable((resId)));
        }

    }
}
